﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
#if _4_LINUX_
using Mono.Data.Sqlite;
#else
using System.Data.SQLite;
#endif
using System.Data;
using Jp.NicoVideo.Live.Api.Properties;

namespace Jp.NicoVideo.Live.Api
{
  internal class CookieMonster
  {
    /// <summary>
    /// 胃袋。
    /// </summary>
    public CookieContainer Stomach = new CookieContainer();

    /// <summary>
    /// 食べる。
    /// </summary>
    public bool Eat()
    {
#if _4_LINUX_
            using (SqliteConnection connection = new SqliteConnection(Settings.Default.cookiesConnectionString4Linux))
            using (SqliteDataAdapter adapter = new SqliteDataAdapter(Settings.Default.cookiesCommandString, connection))
#else
      using (SQLiteConnection connection = new SQLiteConnection(Settings.Default.cookiesConnectionString4Windows))
      using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(Settings.Default.cookiesCommandString, connection))
#endif
      using (DataTable table = new DataTable())
      {
        adapter.Fill(table);
        foreach (DataRow row in table.Rows)
        {
          this.Stomach.Add(new Cookie(
              row["name"] as String,
              row["value"] as String,
              row["path"] as String,
              row["host"] as String));
        }
      }

      return this.Stomach.Count == 0 ? false : true;
    }

    /// <summary>
    /// 吐く。
    /// </summary>
    public static CookieContainer Vomit()
    {
      CookieContainer container = new CookieContainer();
#if _4_LINUX_
            using (SqliteConnection connection = new SqliteConnection(Settings.Default.cookiesConnectionString4Linux))
            using (SqliteDataAdapter adapter = new SqliteDataAdapter(Settings.Default.cookiesCommandString, connection))
#else
      using (SQLiteConnection connection = new SQLiteConnection(Settings.Default.cookiesConnectionString4Windows))
      using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(Settings.Default.cookiesCommandString, connection))
#endif
      using (DataTable table = new DataTable())
      {
        adapter.Fill(table);
        foreach (DataRow row in table.Rows)
        {
          container.Add(new Cookie(
              row["name"] as String,
              row["value"] as String,
              row["path"] as String,
              row["host"] as String));
        }
      }

      return container;
    }

#if todo
    /// <summary>
    /// クッキーファイルのパスを検索します。
    /// </summary>
    /// <returns></returns>
    public static string SearchCookieFilePath()
    {
      string appData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
      appData += @"%appdata%\Roaming\Mozilla\Firefox";
#if _4_LINUX_
      return Settings.Default.cookiesConnectionString4Linux;
#else
      return Settings.Default.cookiesConnectionString4Windows;
#endif
    }
#endif
  }
}
